%% @author Tran Hoan <hoantv3@viettel.com.vn>
%% Copyright Softswitch Viettel  2012-2013. All Rights Reserved
%% Created on 11:39:58 AM Nov 09, 2013
%% Purpose : This module implement behavior for sdl fsm
%% Description: This module copy code from OTP gen_fsm and add some modification for SDL

%% maintainer Tran Hoan

-module(sdl_process).

-export([start/3,
		 start/4,
		 start_link/3,
		 start_link/4
		]).

-export([send_event/2,
		 sync_send_event/2,
		 sync_send_event/3,
		 send_event_after/2,
		 reply/2,
		 start_timer/2,
		 cancel_timer/1
		]).


%% Internal exports
-export([init_it/6,
		 system_continue/3,
		 system_terminate/4,
		 system_code_change/4,
		 format_status/2,
		 wake_hib/7
]).

%% Behavior call back
-callback init(Args :: term()) ->
    {ok, StateName :: atom(), StateData :: term()} |
    {ok, StateName :: atom(), StateData :: term(), timeout() | hibernate} |
    {stop, Reason :: term()} | ignore.
-callback handle_info(Info :: term(), StateName :: atom(),StateData :: term()) ->
    {next_state, NextStateName :: atom(), NewStateData :: term()} |
	{next_state, NextStateName :: atom(), NewStateData :: term(),
								{dequeue, DequeueName :: atom()}} |
    {next_state, NextStateName :: atom(), NewStateData :: term(),
     timeout() | hibernate} |
	{next_state, NextStateName :: atom(), NewStateData :: term(),
     timeout() | hibernate, {dequeue, DequeueName :: atom()}} |
    {stop, Reason :: normal | term(), NewStateData :: term()}.
-callback terminate(Reason :: normal | shutdown | {shutdown, term()}
		    | term(), StateName :: atom(), StateData :: term()) ->
    term().
-callback code_change(OldVsn :: term() | {down, term()}, StateName :: atom(),
		      StateData :: term(), Extra :: term()) ->
    {ok, NextStateName :: atom(), NewStateData :: term()}.

%% Starting function
start(Mod, Args, Options) ->
    gen:start(?MODULE, nolink, Mod, Args, Options).

start(Name, Mod, Args, Options) ->
    gen:start(?MODULE, nolink, Name, Mod, Args, Options).

start_link(Mod, Args, Options) ->
    gen:start(?MODULE, link, Mod, Args, Options).

start_link(Name, Mod, Args, Options) ->
    gen:start(?MODULE, link, Name, Mod, Args, Options).


%% event passing
send_event({global, Name}, Event) ->
    catch global:send(Name, {'$gen_event', Event}),
    ok;
send_event({via, Mod, Name}, Event) ->
    catch Mod:send(Name, {'$gen_event', Event}),
    ok;
send_event(Name, Event) ->
    Name ! {'$gen_event', Event},
    ok.

sync_send_event(Name, Event) ->
    case catch gen:call(Name, '$gen_sync_event', Event) of
	{ok,Res} ->
	    Res;
	{'EXIT',Reason} ->
	    exit({Reason, {?MODULE, sync_send_event, [Name, Event]}})
    end.

sync_send_event(Name, Event, Timeout) ->
    case catch gen:call(Name, '$gen_sync_event', Event, Timeout) of
	{ok,Res} ->
	    Res;
	{'EXIT',Reason} ->
	    exit({Reason, {?MODULE, sync_send_event, [Name, Event, Timeout]}})
    end.

%% Returns Ref, sends event {timeout,Ref,Msg} after Time 
%% to the (then) current state.
-spec start_timer(Time :: timeout(), Msg :: term()) -> Ref when Ref :: reference().
start_timer(Time, Msg) ->
    erlang:start_timer(Time, self(), {'$gen_timer', Msg}).

%% Returns Ref, sends Event after Time to the (then) current state.
-spec send_event_after(Time ::timeout(), Event :: term()) -> Ref when Ref :: reference().
send_event_after(Time, Event) ->
    erlang:start_timer(Time, self(), {'$gen_event', Event}).

%% Timer handling
-spec cancel_timer(Ref :: reference()) -> false | timeout().
cancel_timer(Ref) ->
    case erlang:cancel_timer(Ref) of
	false ->
	    receive {timeout, Ref, _} -> 0
	    after 0 -> false 
	    end;
	RemainingTime ->
	    RemainingTime
    end.

%% Do start

%% Dispatch to FSM
%% async event
dispatch({'$gen_event', Event}, Mod, StateName, StateData) ->
    Mod:StateName(Event, StateData);
%% sync event
dispatch({'$gen_sync_event', From, Event}, Mod, StateName, StateData) ->
    Mod:StateName(Event, From, StateData);
%% state timeout
dispatch({timeout, Ref, {'$gen_timer', Msg}}, Mod, StateName, StateData) ->
    Mod:StateName({timeout, Ref, Msg}, StateData);
%% event timeout
dispatch({timeout, _Ref, {'$gen_event', Event}}, Mod, StateName, StateData) ->
    Mod:StateName(Event, StateData);
%% info message
dispatch(Info, Mod, StateName, StateData) ->
    Mod:handle_info(Info, StateName, StateData).

%% from
from({'$gen_sync_event', From, _Event}) -> From;
from(_) -> undefined.

%% Send a reply to the client.
reply({To, Tag}, Reply) ->
    catch To ! {Tag, Reply}.

reply(Name, {To, Tag}, Reply, Debug, StateName) ->
    reply({To, Tag}, Reply),
    sys:handle_debug(Debug, fun print_event/3, Name,
		     {out, Reply, To, StateName}).

%%% ---------------------------------------------------
%%% Initiate the new process.
%%% Register the name using the Rfunc function
%%% Calls the Mod:init/Args function.
%%% Finally an acknowledge is sent to Parent and the main
%%% loop is entered.
%%% ---------------------------------------------------
init_it(Starter, self, Name, Mod, Args, Options) ->
    init_it(Starter, self(), Name, Mod, Args, Options);
init_it(Starter, Parent, Name0, Mod, Args, Options) ->
    Name = name(Name0),
    Debug = gen:debug_options(Options),
	%% Write parent info to dictionary
	put('$parent',Parent),
    case catch Mod:init(Args) of
	{ok, StateName, StateData} ->
	    proc_lib:init_ack(Starter, {ok, self()}), 	    
	    loop(Parent, Name, StateName, StateData, Mod, infinity,default,Debug);
	{ok, StateName, StateData,{dequeue,DequeName}} ->
		proc_lib:init_ack(Starter, {ok, self()}),
		loop(Parent, Name, StateName, StateData, Mod, infinity,DequeName,Debug);
	{ok, StateName, StateData, Timeout} ->
	    proc_lib:init_ack(Starter, {ok, self()}), 	    
	    loop(Parent, Name, StateName, StateData, Mod, Timeout,default,Debug);
	{ok, StateName, StateData, Timeout,{dequeue,DequeName}} ->
	    proc_lib:init_ack(Starter, {ok, self()}), 	    
	    loop(Parent, Name, StateName, StateData, Mod, Timeout,DequeName,Debug);
	{stop, Reason} ->
	    unregister_name(Name0),
	    proc_lib:init_ack(Starter, {error, Reason}),
	    exit(Reason);
	ignore ->
	    unregister_name(Name0),
	    proc_lib:init_ack(Starter, ignore),
	    exit(normal);
	{'EXIT', Reason} ->
	    unregister_name(Name0),
	    proc_lib:init_ack(Starter, {error, Reason}),
	    exit(Reason);
	Else ->
	    Error = {bad_return_value, Else},
	    proc_lib:init_ack(Starter, {error, Error}),
	    exit(Error)
    end.


name({local,Name}) -> Name;
name({global,Name}) -> Name;
name({via,_, Name}) -> Name;
name(Pid) when is_pid(Pid) -> Pid.

unregister_name({local,Name}) ->
    _ = (catch unregister(Name));
unregister_name({global,Name}) ->
    _ = global:unregister_name(Name);
unregister_name({via, Mod, Name}) ->
    _ = Mod:unregister_name(Name);
unregister_name(Pid) when is_pid(Pid) ->
    Pid.

%% main loop
loop(Parent, Name, StateName, StateData, Mod, hibernate,DequeueName,Debug) ->
    proc_lib:hibernate(?MODULE,wake_hib,
		       [Parent, Name, StateName, StateData, 
				Mod, DequeueName, Debug]);

loop(Parent, Name, StateName, StateData, Mod, Time,default,Debug) ->
    Msg = receive
	      Input ->
		    Input
	  after Time ->
		  {'$gen_event', timeout}
	  end,
    decode_msg(Msg,Parent, Name, StateName, StateData, 
			   Mod, Time,default, Debug, false);

loop(Parent, Name, StateName, StateData, Mod,Time,DequeueName,Debug) ->
	case catch Mod:DequeueName(Time) of
		Msg ->
			decode_msg(Msg,Parent, Name, StateName, StateData, 
			   Mod, Time,DequeueName, Debug, false)
	end.

wake_hib(Parent, Name, StateName, StateData, Mod, default, Debug) ->
    Msg = receive
	      Input ->
		  Input
	  end,
    decode_msg(Msg, Parent, Name, StateName, StateData, 
			   Mod, hibernate,default, Debug, true);

wake_hib(Parent, Name, StateName, StateData, Mod, DequeueName, Debug) ->
    case catch Mod:DequeueName(infinity) of
		Msg ->
			decode_msg(Msg, Parent, Name, StateName, StateData,
			   Mod, hibernate,DequeueName, Debug, true)
	end.

%% rewrite decode_msg
decode_msg(Msg,Parent, Name, StateName, StateData, Mod, Time, DequeueName ,Debug, Hib) ->
    case Msg of
	{system, From, get_state} ->
	    Misc = [Name, StateName, StateData, Mod, Time, DequeueName],
	    sys:handle_system_msg(get_state, From, Parent, ?MODULE, Debug,
				  {{StateName, StateData}, Misc}, Hib);
	{system, From, {replace_state, StateFun}} ->
	    State = {StateName, StateData},
	    NState = {NStateName, NStateData} = try StateFun(State)
						catch _:_ -> State end,
	    NMisc = [Name, NStateName, NStateData, Mod, Time, DequeueName],
	    sys:handle_system_msg(replace_state, From, Parent, ?MODULE, Debug,
				  {NState, NMisc}, Hib);
        {system, From, Req} ->
	    sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
				  [Name, StateName, StateData, Mod, Time, DequeueName],Hib);
	{'EXIT', Parent, Reason} ->
	    terminate(Reason, Name, Msg, Mod, StateName, StateData,Debug);
	_Msg when Debug =:= [] ->
	    handle_msg(Msg, Parent, Name, StateName, StateData, Mod, Time);
	_Msg ->
	    Debug1 = sys:handle_debug(Debug, fun print_event/3,
				      {Name, StateName}, {in, Msg}),
	    handle_msg(Msg, Parent, Name, StateName, StateData,Mod, Time,Debug1)
    end.

%% Handle message

handle_msg(Msg, Parent, Name, StateName, StateData, Mod,_Time) -> %No debug here
    From = from(Msg),
    case catch dispatch(Msg, Mod, StateName, StateData) of
	%% handle async return event
	{next_state, NStateName, NStateData} ->	    
	    loop(Parent, Name, NStateName, NStateData, Mod, infinity, default, []);
	{next_state, NStateName, NStateData, {dequeue,DequeueName}} ->
		loop(Parent, Name, NStateName, NStateData, Mod, infinity, DequeueName, []);
	{next_state, NStateName, NStateData, Time1} ->
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1, default, []);
	{next_state, NStateName, NStateData, Time1,{dequeue,DequeueName}} ->
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1, DequeueName, []);
	%% handle sync return event
    {reply, Reply, NStateName, NStateData} when From =/= undefined ->
	    reply(From, Reply),
	    loop(Parent, Name, NStateName, NStateData, Mod, infinity, default, []);
	{reply, Reply, NStateName, NStateData,{dequeue,DequeueName}} when From =/= undefined ->
	    reply(From, Reply),
	    loop(Parent, Name, NStateName, NStateData, Mod, infinity, DequeueName, []);
    {reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
	    reply(From, Reply),
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1, default, []);
 	{reply, Reply, NStateName, NStateData, Time1,{dequeue,DequeueName}} when From =/= undefined ->
	    reply(From, Reply),
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1, DequeueName, []);
	%% handle stop event
	{stop, Reason, NStateData} ->
	    terminate(Reason, Name, Msg, Mod, StateName, NStateData,[]);
	{stop, Reason, Reply, NStateData} when From =/= undefined ->
	    {'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
									   StateName, NStateData,[])),
	    reply(From, Reply),
	    exit(R);
	{'EXIT', What} ->
	    terminate(What, Name, Msg, Mod, StateName, StateData,[]);
	Reply ->
	    terminate({bad_return_value, Reply},
		      Name, Msg, Mod, StateName, StateData,[])
    end.

handle_msg(Msg, Parent, Name, StateName, StateData, Mod,_Time,Debug) ->
    From = from(Msg),
    case catch dispatch(Msg, Mod, StateName, StateData) of
	%% handle async return event
	{next_state, NStateName, NStateData} ->
	    Debug1 = sys:handle_debug(Debug, fun print_event/3,
				      {Name, NStateName}, return),
	    loop(Parent, Name, NStateName, NStateData, Mod, infinity,default, Debug1);
	{next_state, NStateName, NStateData, {dequeue,DequeueName}} ->
		Debug1 = sys:handle_debug(Debug, fun print_event/3,
				      {Name, NStateName}, return),
	    loop(Parent, Name, NStateName, NStateData, Mod, infinity,DequeueName, Debug1);
	{next_state, NStateName, NStateData, Time1} ->
	    Debug1 = sys:handle_debug(Debug, fun print_event/3,{Name, NStateName}, return),
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1,default, Debug1);
	{next_state, NStateName, NStateData, Time1,{dequeue,DequeueName}} ->
	    Debug1 = sys:handle_debug(Debug, fun print_event/3,{Name, NStateName}, return),
	    loop(Parent, Name, NStateName, NStateData, Mod, Time1,DequeueName, Debug1);
	%% handle sync return event
    {reply, Reply, NStateName, NStateData} when From =/= undefined ->
		Debug1 = reply(Name, From, Reply, Debug, NStateName),
		loop(Parent, Name, NStateName, NStateData, Mod, infinity,default, Debug1);
	{reply, Reply, NStateName, NStateData,{dequeue,DequeueName}} when From =/= undefined ->
		Debug1 = reply(Name, From, Reply, Debug, NStateName),
		loop(Parent, Name, NStateName, NStateData, Mod, infinity,DequeueName, Debug1);
	{reply, Reply, NStateName, NStateData, Time1} when From =/= undefined ->
		Debug1 = reply(Name, From, Reply, Debug, NStateName),
		loop(Parent, Name, NStateName, NStateData, Mod, Time1,default, Debug1);
    {reply, Reply, NStateName, NStateData, Time1,{dequeue,DequeueName}} when From =/= undefined ->
		Debug1 = reply(Name, From, Reply, Debug, NStateName),
		loop(Parent, Name, NStateName, NStateData, Mod, Time1,DequeueName, Debug1);
	%% handle stop event
	{stop, Reason, NStateData} ->
	    terminate(Reason, Name, Msg, Mod,
				  StateName, NStateData,Debug);
	{stop, Reason, Reply, NStateData} when From =/= undefined ->
	    {'EXIT', R} = (catch terminate(Reason, Name, Msg, Mod,
									   StateName, NStateData,Debug)),
	    reply(Name, From, Reply, Debug, StateName),
	    exit(R);
	{'EXIT', What} ->
	    terminate(What, Name, Msg, Mod, StateName, StateData,Debug);
	Reply ->
	    terminate({bad_return_value, Reply},
		      Name, Msg, Mod, StateName, StateData,Debug)
    end.



%%-----------------------------------------------------------------
%% Callback functions for system messages handling.
%%-----------------------------------------------------------------
system_continue(Parent, Debug, [Name, StateName, StateData, Mod, Time, DequeueName]) ->
    loop(Parent, Name, StateName, StateData, Mod, Time, DequeueName, Debug).

-spec system_terminate(term(), _, _, [term(),...]) -> no_return().

system_terminate(Reason, _Parent, Debug,
		 [Name, StateName, StateData, Mod, _Time]) ->
    terminate(Reason, Name, [], Mod, StateName, StateData,Debug).

system_code_change([Name, StateName, StateData, Mod, Time],
		   _Module, OldVsn, Extra) ->
    case catch Mod:code_change(OldVsn, StateName, StateData, Extra) of
	{ok, NewStateName, NewStateData} ->
	    {ok, [Name, NewStateName, NewStateData, Mod, Time]};
	Else -> Else
    end.

-spec terminate(term(), _, _, atom(), _, _, _) -> no_return().

terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug) ->
    case catch Mod:terminate(Reason, StateName, StateData) of
	{'EXIT', R} ->
	    error_info(R, Name, Msg, StateName, StateData,Debug),
	    exit(R);
	_ ->
	    case Reason of
		normal ->
		    exit(normal);
		shutdown ->
		    exit(shutdown);
 		{shutdown,_}=Shutdown ->
 		    exit(Shutdown);
		_ ->
                    FmtStateData =
                        case erlang:function_exported(Mod, format_status, 2) of
                            true ->
                                Args = [get(), StateData],
                                case catch Mod:format_status(terminate, Args) of
                                    {'EXIT', _} -> StateData;
                                    Else -> Else
                                end;
                            _ ->
                                StateData
                        end,
		    error_info(Reason,Name,Msg,StateName,FmtStateData,Debug),
		    exit(Reason)
	    end
    end.

error_info(Reason, Name, Msg, StateName, StateData,Debug) ->
    Reason1 = 
	case Reason of
	    {undef,[{M,F,A,L}|MFAs]} ->
		case code:is_loaded(M) of
		    false ->
			{'module could not be loaded',[{M,F,A,L}|MFAs]};
		    _ ->
			case erlang:function_exported(M, F, length(A)) of
			    true ->
				Reason;
			    false ->
				{'function not exported',[{M,F,A,L}|MFAs]}
			end
		end;
	    _ ->
		Reason
	end,
    Str = "** SDL process ~p terminating \n" ++
	get_msg_str(Msg) ++
	"** When State == ~p~n"
        "**      Data  == ~p~n"
        "** Reason for termination = ~n** ~p~n",
    error_logger:format(Str, [Name, get_msg(Msg), StateName, StateData, Reason1]),
    sys:print_log(Debug),
    ok.

get_msg_str({'$gen_event', _Event}) ->
    "** Last event in was ~p~n";
get_msg_str({'$gen_sync_event', _Event}) ->
    "** Last sync event in was ~p~n";
get_msg_str({timeout, _Ref, {'$gen_timer', _Msg}}) ->
    "** Last timer event in was ~p~n";
get_msg_str({timeout, _Ref, {'$gen_event', _Msg}}) ->
    "** Last timer event in was ~p~n";
get_msg_str(_Msg) ->
    "** Last message in was ~p~n".

get_msg({'$gen_event', Event}) -> Event;
get_msg({'$gen_sync_event', Event}) -> Event;
get_msg({timeout, Ref, {'$gen_timer', Msg}}) -> {timeout, Ref, Msg};
get_msg({timeout, _Ref, {'$gen_event', Event}}) -> Event;
get_msg(Msg) -> Msg.

%%-----------------------------------------------------------------
%% Format debug messages.  Print them as the call-back module sees
%% them, not as the real erlang messages.  Use trace for that.
%%-----------------------------------------------------------------
print_event(Dev, {in, Msg}, {Name, StateName}) ->
    case Msg of
	{'$gen_event', Event} ->
	    io:format(Dev, "*DBG* ~p got event ~p in state ~w~n",
		      [Name, Event, StateName]);
	{timeout, Ref, {'$gen_timer', Message}} ->
	    io:format(Dev,
		      "*DBG* ~p got timer ~p in state ~w~n",
		      [Name, {timeout, Ref, Message}, StateName]);
	{timeout, _Ref, {'$gen_event', Event}} ->
	    io:format(Dev,
		      "*DBG* ~p got timer ~p in state ~w~n",
		      [Name, Event, StateName]);
	_ ->
	    io:format(Dev, "*DBG* ~p got ~p in state ~w~n",
		      [Name, Msg, StateName])
    end;
print_event(Dev, {out, Msg, To, StateName}, Name) ->
    io:format(Dev, "*DBG* ~p sent ~p to ~w~n"
	           "      and switched to state ~w~n",
	      [Name, Msg, To, StateName]);
print_event(Dev, return, {Name, StateName}) ->
    io:format(Dev, "*DBG* ~p switched to state ~w~n",
	      [Name, StateName]).

%%-----------------------------------------------------------------
%% Status information
%%-----------------------------------------------------------------
format_status(Opt, StatusData) ->
    [PDict, SysState, Parent, Debug, [Name, StateName, StateData, Mod, _Time]] =
	StatusData,
    Header = gen:format_status_header("Status for SDL process",
                                      Name),
    Log = sys:get_debug(log, Debug, []),
    DefaultStatus = [{data, [{"StateData", StateData}]}],
    Specfic =
	case erlang:function_exported(Mod, format_status, 2) of
	    true ->
		case catch Mod:format_status(Opt,[PDict,StateData]) of
		    {'EXIT', _} -> DefaultStatus;
                    StatusList when is_list(StatusList) -> StatusList;
		    Else -> [Else]
		end;
	    _ ->
		DefaultStatus
	end,
    [{header, Header},
     {data, [{"Status", SysState},
	     {"Parent", Parent},
	     {"Logged events", Log},
	     {"StateName", StateName}]} |
     Specfic].